#include "TheApp.hpp"
//#include "cybertron/core/UtilUrlRequest.hpp"
#include "cybertron/core/Log.hpp"
#include "cybertron/core/UtilPath.hpp"
#include "cybertron/core/Thread.hpp"
#include "cybertron/core/UtilConsole.hpp"
#include "cybertron/core/UtilCRT.hpp"
#include "cybertron/node/StartupArguments.hpp"
#include "cybertron/core/CoreVersion.hpp"
#include "cybertron/core/SimOneEnv.hpp"
#include "cybertron/core/UtilUuidxx.hpp"
#include <iostream>
#include <fstream>
#include <chrono>
#ifdef CYBERTRON_LINUX
#include <unistd.h>
#include <stdlib.h>  
#include <signal.h>
#endif
// determined by the EnvVar LOG_CONSOLE outside on the windows
//#if defined(CYBERTRON_WIN) && defined(NDEBUG)
//#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
//#endif

using namespace cybertron;

//
static UtilCRTAutoInitialize sCRT;

#ifdef CYBERTRON_LINUX
bool gRunning = true;
void sigterm_handler(int no) {
	gRunning = false;
	logInfo("recv sigterm_handler exit....%d", no);
}
#endif

TheApp::TheApp()
{
	BaseApp::mInstance = this;
	mWorkNodeType = Common::EWorkNodeType_CybertronNodeTimer;
	mbRunning = true;
	mNodeTimeIp = "127.0.0.1";
	mNodeTimePort = 0;
}
TheApp::~TheApp()
{

}

void TheApp::getVerion()
{
	std::string version = getVersionOnCore("CybertronWork", "20210626154200");
	logInfo("%s", version.c_str());
}

bool TheApp::init(int argc, char* argv[])
{
	if(!WorkApp::init(argc, argv)){
		return false;
	}
	mpServer = std::make_shared<TimeServer>();
	if (!mpServer->initialize())
	{
		logError("Failed to initialize server!");
		return false;
	}
	mpServer->listen(mNodeTimePort);
	mNodeTimePort = mpServer->getListenPort();
	logInfo("========> NodeTimer Listen Port:%d <======== ",mNodeTimePort);
	setServerListenPort(mNodeTimePort);
	return true;
}

int TheApp::run()
{
	UtilCRT::call("runDaemon", [this]() {
		this->runDaemon();
	});
	return 0;
}

void TheApp::runDaemon() {
	mpServer->run();
	mpServer->close();
	mpServer = nullptr;
}
///////////////////////////////////////////////////
void TheApp::onWorkNodeStop() {
	logInfo("===========>onWorkNodeStop <===========");
	mpServer->exit();
	mbRunning = false;
	stopRunning();
	
}
bool TheApp::onTaskStartBefore() {

	Agent::WorkNodeRegisterRet* pWorkNodeRegisterRetData = getWorkNodeRegisterRetData();
	mpServer->loadConfigFromAgent(pWorkNodeRegisterRetData);
	return WorkApp::onTaskStartBefore();
}

bool TheApp::onTaskStart() {
	logInfo("===========>onTaskStart <===========");

	return true;
}
bool TheApp::onTaskRunning() {
	logInfo("===========>onTaskRunning <===========");
	mpServer->setTimeStart();
	return true;
}
bool TheApp::onTaskStop() {
	logInfo("===========>onTaskStop <===========");
	mbRunning = false;
	return true;
}